//
//  MaterialAcceptHomeController.m
//  ERP
//
//  Created by QA on 2016/10/17.
//  Copyright © 2016年 ShangHai HaoLei Software Technology Co., Ltd. All rights reserved.
//

#import "MaterialAcceptHomeController.h"

#import "MJRefresh.h"
#import "MaterialAcceptListCell.h"
#import "MaterialAcceptHomeCell.h"

#import "UITableView+Custom.h"

#import "NSDictionary+DataFormat.h"
#import "WebServiceCommonRequest.h"

#import "MaterialAcceptMaterialController.h"
#import "MaterialAcceptListController.h"
#import "MaterialAcceptCreateController.h"

@interface MaterialAcceptHomeController ()

@property (nonatomic, strong) IBOutlet UITableView *tableView;
@property (strong, nonatomic) NSMutableArray *resultData;
@property (nonatomic, assign) NSInteger orderContentState;//0加载中，1未找到数据，2加载失败，3加载成功

@end

@implementation MaterialAcceptHomeController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        [self setTitle:@"原材抽检"];
        [self addStationToNavigationItem];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.resultData = [NSMutableArray array];
    self.tableView.tableFooterView= [[UIView alloc] init];
    
    //添加下拉加载数据
    [self.tableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    
    //[self.tableView headerBeginRefreshing];
    [self getNetWorkDataIsReresh:YES state:@1 end:@10];
}

#pragma make - Station Notification

-(void)updateStationNotification:(StationInfoEntity*)model
{
    //[self.tableView removeAllSaveCell];
    [self.resultData removeAllObjects];
    self.orderContentState = 0;
    [self.tableView reloadData];
    
    [self getNetWorkDataIsReresh:YES state:@1 end:@10];
}

#pragma mark 网络获取数据

- (void)getNetWorkDataIsReresh:(BOOL)isReresh state:(NSNumber*)state end:(NSNumber*)end
{
    //站点ID
    StationInfoEntity *model = [[GetUserStationService sharedService] getSelectStationEntity];
    
    //@状态（1待验收，2已验收）
    WebServiceCommonRequest *content = [[WebServiceCommonRequest alloc] init];
    [content setInterfaceType:InterfaceTypeERP];
    [content setModuleType:@"YCQS_LIST"];
    [content setResultBackType:ResultBackTypeCommonUnordered];
    [content setStationID:[model.stationId integerValue]];
    
    [content addParameterKey:@"起始条数" value:state];
    [content addParameterKey:@"结束条数" value:end];
    [content addParameterKey:@"查询类型" value:@1];
    [content addParameterKey:@"材料ID" value:@0];
    [content addParameterKey:@"供应商ID" value:@0];
    [content addParameterKey:@"站点ID" value:model.stationId];
    
    [content startAsyncConnectCompleted:^(ServiceResultModel *result, NSDictionary *userInfo) {
        if(isReresh) [self.tableView headerEndRefreshing];
        else [self.tableView footerEndRefreshing];
        
        //添加数据，刷新页面
        NSArray *firstArray = nil;
        if(result.resultArray && result.resultArray.count>0)
            firstArray = [result.resultArray firstObject];
        
        if(isReresh) [self.resultData removeAllObjects];
        if(firstArray && firstArray.count>0){
            [self.resultData addObjectsFromArray:firstArray];
            self.orderContentState = 3;
        } else if(isReresh){
            self.orderContentState = 1;
        }
        [self.tableView reloadData];
        
    } failed:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        self.orderContentState = 2;
        [self.tableView reloadData];
        
    } abnormal:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        self.orderContentState = 2;
        [self.tableView reloadData];
    }];
    
}

- (void)errorInfoViewText:(NSString*)label
{
    [self.tableView headerEndRefreshing];
    [self.tableView footerEndRefreshing];
    
    if (self.tableView.visibleCells.count <= 0) {
        [self.tableView setTableViewNotDataDrawText:label isShow:YES];
    } else {
        [self.tableView setTableViewNotDataDrawText:nil isShow:NO];
        [self showErrorHUDText:label];
    }
}

#pragma mark 开始进入刷新状态

- (void)headerRereshing
{
    NSNumber *stateNumber = [NSNumber numberWithInteger:0];
    NSNumber *endNumber = [NSNumber numberWithInteger:10];
    [self getNetWorkDataIsReresh:YES state:stateNumber end:endNumber];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [tableView setLayoutMargins:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(section == 1) {
        NSInteger count = self.resultData.count;
        return count > 0 ? count : 1;
    } else {
        return 1;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == 0){
        static NSString *Identifier = @"MaterialAcceptHomeCell";
        MaterialAcceptHomeCell *cell = [tableView dequeueReusableCellWithIdentifier:Identifier];
        if (!cell){
            cell = [[MaterialAcceptHomeCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:Identifier index:0];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(OnTapBtnView:)];
            [cell.mView01 addGestureRecognizer:tap1];
            cell.mView01.tag = 1;
            
            UITapGestureRecognizer *tap2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(OnTapBtnView:)];
            [cell.mView02 addGestureRecognizer:tap2];
            cell.mView02.tag = 2;
        }
        return cell;
        
    } else {
        if (self.orderContentState == 3) {
            static NSString *Identifier = @"MTCContractHomeViewCell";
            MaterialAcceptListCell *cell = [tableView dequeueReusableCellWithIdentifier:Identifier];
            if (!cell){
                cell = [[MaterialAcceptListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:Identifier];
            }
            
            NSDictionary *model = [self.resultData objectAtIndex:indexPath.row];
            cell.compyLable.text = [model objectFormatStringForKey:@"供应商" defaults:@"未知"];
            cell.jcsjLable.text = [model objectFormatStringForKey:@"进厂时间" format:@"%@方" defaults:@"未知"];
            cell.stateLable.text = [model objectFormatStringForKey:@"状态" format:@"%@" defaults:@"未知"];
            cell.clmzLable.text = [model objectFormatFloatStringForKey:@"毛重" retain:1 except:1000 exceptFormat:@"%@吨" format:@"%@公斤"];

            NSString *carNumber = [model objectFormatStringForKey:@"车辆编号" defaults:@"未知"];
            NSString *clType = [model objectFormatStringForKey:@"材料名称" defaults:@"未知"];
            cell.carNumberLable.text = [NSString stringWithFormat:@"%@ (%@)",carNumber,clType];
            
            return cell;
            
        } else {
            UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"MTCClienterDetailHT"];
            cell.contentView.frame = CGRectMake(0, 0, SuperWidth, 55);
            
            if(self.orderContentState == 0) {//加载进度条
                UIActivityIndicatorView *act=[[UIActivityIndicatorView  alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
                act.center = CGPointMake(SuperWidth/2, 30.0f);
                act.activityIndicatorViewStyle=UIActivityIndicatorViewStyleGray;
                act.hidesWhenStopped = YES;
                [act startAnimating];
                [cell.contentView addSubview:act];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                
            } else if(self.orderContentState == 1){//显示无数据提示
                UILabel* label = [[UILabel alloc] initWithFrame:cell.contentView.frame];
                label.text = @"暂无过磅单";
                label.font = [UIFont fontWithName:@"Arial" size:16];
                label.textColor = [UIColor lightGrayColor];
                label.textAlignment = NSTextAlignmentCenter;
                [cell.contentView addSubview:label];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                
            } else if(self.orderContentState == 2){//显示失败提示
                UILabel* label = [[UILabel alloc] initWithFrame:cell.contentView.frame];
                label.text = @"加载合同失败，点击重试";
                label.font = [UIFont fontWithName:@"Arial" size:16];
                label.textColor = [UIColor lightGrayColor];
                label.textAlignment = NSTextAlignmentCenter;
                [cell.contentView addSubview:label];
            }
            return cell;
        }
        
    }
}

#pragma mark
#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if(section == 0) return 0.00000001;
    return 30;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SuperWidth, 30)];
    view.backgroundColor = [UIColor whiteColor];
    if(section == 0) return view;
    
    UILabel *lable = [[UILabel alloc] initWithFrame:CGRectMake(8, 0, SuperWidth - 10, 29.5)];
    lable.textColor = [UIColor darkGrayColor];
    lable.font = [UIFont boldSystemFontOfSize:15];
    lable.text = @"最新材料过磅单";
    [view addSubview:lable];
    
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 15;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == 0) return 80;
    if (indexPath.row >= self.resultData.count) return 54;
    return 82;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if(indexPath.section == 0) return;
    
    if (indexPath.section == 1) {
        if(self.orderContentState == 2) {//加载失败执行
            self.orderContentState = 0;
            [self.tableView reloadData];
            [self getNetWorkDataIsReresh:YES state:@1 end:@10];
            
        } else if(self.orderContentState == 3) { //加载成功
            NSDictionary *model = [self.resultData objectAtIndex:indexPath.row];
            NSInteger state = [model objectFormatIntegerForKey:@"status"];
            if(state != 1) return;//1待验收状态
            
            MaterialAcceptCreateController *mOrderDetails = [[MaterialAcceptCreateController alloc] initWithValue:model];
            mOrderDetails.backResultDelagate = self;
            [self.navigationController pushViewController:mOrderDetails animated:YES];
        }
    }
}

#pragma mark
#pragma mark - BackResultDataDelagate

- (void)backResultDataKey:(id)key dataValue:(id)backValue
{
    if (backValue && [backValue isKindOfClass:[NSDictionary class]]) {
        NSInteger index = [self.resultData indexOfObject:backValue];
        if (index < self.resultData.count) {
            [self.resultData removeObjectAtIndex:index];
            [self.tableView reloadData];
        }
        if(self.resultData.count <= 0)
            [self.tableView setTableViewNotDataDrawText:@"暂无过磅单" isShow:YES];
    }
}

#pragma mark Block && UITapGestureRecognizernt

- (void)OnTapBtnView:(UITapGestureRecognizer *)sender
{
    NSLog(@"tag:%ld",sender.view.tag);
    if(sender.view.tag == 1) {//按车号
        MaterialAcceptListController *view = [[MaterialAcceptListController alloc] init];
        [self.navigationController pushViewController:view animated:YES];
        
    } else if(sender.view.tag == 2) {//按材料查询
        MaterialAcceptMaterialController *view = [[MaterialAcceptMaterialController alloc] init];
        [self.navigationController pushViewController:view animated:YES];
    }

}


@end
